package com.cq.hd.order.render.impl;

import com.alibaba.fastjson.JSON;
import com.cq.hd.common.enums.biz.AgentStateEnum;
import com.cq.hd.common.enums.biz.PromotionTypeEnum;
import com.cq.hd.common.response.Throw;
import com.cq.hd.member.api.TbAppUserApi;
import com.cq.hd.member.api.TbBusinessAgentApi;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.vo.AppUserVo;
import com.cq.hd.member.api.vo.BusinessAgentVo;
import com.cq.hd.member.api.vo.BusinessPageVo;
import com.cq.hd.order.api.dto.CreateOrderDto;
import com.cq.hd.order.po.TbGroupBuyOrderPo;
import com.cq.hd.order.render.OrderContext;
import com.cq.hd.order.render.OrderRenderStepEnum;
import com.cq.hd.order.render.dto.AgentInfo;
import com.cq.hd.order.service.TbGroupBuyOrderService;
import com.cq.hd.product.api.TbActiveShareApi;
import com.cq.hd.product.api.vo.ActiveShareRecordVo;
import com.cq.hd.product.api.vo.ActiveVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 经纪人渲染
 *
 * @author much
 * @since 2024/09/13 22:52
 */
@Slf4j
@Component
public class AgentRender extends AbstractRenderStep {

    @Resource
    private TbActiveShareApi activeShareApi;
    @Resource
    private TbAppUserApi appUserApi;
    @Resource
    private TbBusinessApi businessApi;
    @Resource
    private TbBusinessAgentApi businessAgentApi;
    @Resource
    private TbGroupBuyOrderService groupBuyOrderService;

    @Override
    public OrderRenderStepEnum step() {
        return OrderRenderStepEnum.AGENT;
    }

    @Override
    public void render(OrderContext orderContext) {
        log.info("经纪人渲染:{}", JSON.toJSONString(orderContext));
        CreateOrderDto createOrderDto = orderContext.getCreateOrderDto();
        ActiveVo activeVo = orderContext.getActiveVo();
        if (!AgentStateEnum.OPEN.getValue().equals(activeVo.getAgentState())) {
            return;
        }
        if (createOrderDto.getPromotionType() != null && createOrderDto.getPromotionType() == PromotionTypeEnum.GROUP_BUY) {
            log.info("经纪人渲染 - 拼团:{}", JSON.toJSONString(orderContext));
            renderAgent4GroupBuy(orderContext);
        } else {
            log.info("经纪人渲染 - 普通:{}", JSON.toJSONString(orderContext));
            renderAgent4Normal(orderContext);
        }
    }

    // 拼团经纪人
    private void renderAgent4GroupBuy(OrderContext orderContext) {
        CreateOrderDto createOrderDto = orderContext.getCreateOrderDto();
        // 如果是开团，则按照分享的逻辑
        if (createOrderDto.getGroupBuyOrderId() == null) {
            renderAgent4Normal(orderContext);
        } else {
            // 判断团长是否经纪人
            TbGroupBuyOrderPo groupBuyOrderPo = groupBuyOrderService.getById(createOrderDto.getGroupBuyOrderId());
            orderContext.setGroupBuyOrderPo(groupBuyOrderPo);
            if (groupBuyOrderPo == null) {
                Throw.isBusinessException("拼团不存在");
            }
            Long leadUserId = groupBuyOrderPo.getLeadUserId();
            AppUserVo leadUser = appUserApi.getById(leadUserId).unpack();

            // 如果是策划人自己的活动，则不应该有佣金
            ActiveVo activeVo = orderContext.getActiveVo();
            BusinessPageVo businessVo = businessApi.getById(activeVo.getBusinessId()).unpack();
            if (businessVo.getUserId().equals(leadUserId)) {
                return;
            }

            // 非商家经纪人，没有佣金
            BusinessAgentVo businessAgentVo = businessAgentApi.getBusinessAgentById(activeVo.getBusinessId(), leadUserId).unpack();
            if (businessAgentVo == null) {
                return;
            }

            if (leadUser.getAgentLevel() == 1) {
                // 一级经纪人
                AgentInfo agentInfo = new AgentInfo();
                agentInfo.setAgent1Id(leadUserId);
                agentInfo.setRewardType(groupBuyOrderPo.getRewardType());
                orderContext.setAgentInfo(agentInfo);
            } else if (leadUser.getAgentLevel() == 2) {
                // 二级经纪人
                AgentInfo agentInfo = new AgentInfo();
                agentInfo.setAgent1Id(leadUser.getAgentId());
                agentInfo.setAgent2Id(leadUserId);
                agentInfo.setRewardType(groupBuyOrderPo.getRewardType());
                orderContext.setAgentInfo(agentInfo);
            }
        }
    }

    // 普通活动经纪人
    private void renderAgent4Normal(OrderContext orderContext) {
        CreateOrderDto createOrderDto = orderContext.getCreateOrderDto();
        Long activeId = createOrderDto.getActiveId();
        String code = createOrderDto.getCode();
        if (StringUtils.isBlank(code)) {
            return;
        }
        ActiveShareRecordVo activeShareRecordVo = activeShareApi.getByCode(code, activeId).unpack();
        if (activeShareRecordVo == null || activeShareRecordVo.getDelState() != 0) {
            return;
        }
        // 推广奖励类型（0-无，1-佣金，2-其他权益，3-积分）
        Integer rewardType = activeShareRecordVo.getRewardType();
        if (rewardType == null || rewardType == 0) {
            return;
        }

        // 如果是经纪人分享给自己下单，也不会有佣金/权益
        if (activeShareRecordVo.getUserId().equals(orderContext.getUserId())) {
            return;
        }

        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setAgent1Id(activeShareRecordVo.getAgent1Id()); // 一级经纪人id
        agentInfo.setAgent2Id(activeShareRecordVo.getAgent2Id()); // 二级经纪人id，如果有
        agentInfo.setRewardType(rewardType);
        orderContext.setAgentInfo(agentInfo);
    }

}
